<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      title="选择类目"
      width="850px"
      @close="close"
    >
      <div v-show="businessType == 'ORDER'">
        <el-select
          v-model="shopId"
          style="min-width: 300px"
          placeholder="请选择门店"
        >
          <el-option
            v-for="(item, key) in shopList"
            :key="key"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="tree-content">
        <!-- :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :highlight-current="true"-->
        <el-tree
          ref="categoryTree"
          :data="treeData"
          :props="treeProps"
          default-expand-all
          node-key="id"
          show-checkbox
          @node-click="handleTree"
          @check-change="handleCheckChange"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button
          size="small"
          round
          type="primary"
          @click="submit"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { categoryTree } from '@/views/wxaMallModule/api/category'
import { getAllShop } from '@/api/shop'
import {
  getGoodsList,
  updateGoodsStatus,
  getClassifyList
} from '@/views/wcyModule/api/product'

import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      // 配置
      treeProps: {
        label: 'title'
      },
      resolve: null,
      reject: null,
      // 状态
      loading: false,
      dialogVisible: null,
      // 数据
      treeData: [],
      businessType: 'MALL',
      shopId: '',
      shopList: [],
      orderList: []
    }
  },
  computed: {
    ...mapGetters(['activePageForm'])
  },
  watch: {
    'activePageForm.activeModuleIndex'() {
      this.setbusinessType()
    },
    shopId() {
      this.getProClass()
      const ids = []
      // this.orderList.forEach(item=>{
      //   ids.push(item.id)
      // })
      // this.$refs.categoryTree.setCheckedKeys(ids)
    }
  },
  methods: {
    /**
     * 弹框相关
     */
    open({ categoryIds = [] }) {
      this.setbusinessType()
      this.getTree(categoryIds)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */
    // 获取tree列表
    getTree(categoryIds) {
      this.loading = true
      if (this.businessType == 'MALL') {
        categoryTree()
          .then((res) => {
            this.treeData = res.data
            this.$nextTick(() => {
              this.$refs.categoryTree.setCheckedKeys(categoryIds)
            })
          })
          .catch((err) => {})
          .finally(() => {
            this.loading = false
          })
      } else {
        const ids = []
        categoryIds.forEach((v) => {
          if (v.id) {
            ids.push(v.id)
          } else {
            ids.push(v.classifyId)
          }
        })
        this.orderList = categoryIds
        this.$nextTick(() => {
          this.$refs.categoryTree.setCheckedKeys(ids)
        })
        this.getShopList()
      }
    },

    /**
     * 按钮组
     */
    // 确 定
    submit() {
      const checkIds = this.$refs.categoryTree.getCheckedKeys()
      var categoryList = []
      var { businessType } = this
      var _this = this
      getCategoryList(this.treeData)
      function getCategoryList(data, titles = []) {
        if (businessType == 'MALL') {
          data.forEach((v) => {
            let names = []
            if (checkIds.includes(v.id)) {
              names = titles.concat([v.title])
              categoryList.push({
                names: names,
                id: v.id,
                title: v.title
              })
            }
            if (v.children && v.children.length > 0) {
              getCategoryList(v.children, names)
            }
          })
        } else {
          categoryList = _this.orderList
          console.log(categoryList)
        }
      }
      this.resolve && this.resolve(categoryList)
      this.hide()
    },

    // 点击tree
    handleTree(data, node, ref) {
      // this.$refs.categoryTree.setChecked(data, !node.checked);
    },
    handleCheckChange(data, checked) {
      if (this.orderList.length > 0) {
        if (checked) {
          if (Object.keys(this.orderList[0]).includes('id')) {
            this.orderList.findIndex((item) => item.id == data.id) == -1
              ? this.orderList.push(data)
              : ''
          } else {
            this.orderList.findIndex((item) => item.classifyId == data.id) == -1
              ? this.orderList.push(data)
              : ''
          }
        } else {
          if (Object.keys(this.orderList[0]).includes('id')) {
            this.orderList.forEach((ele, index) => {
              ele.id == data.id ? this.orderList.splice(index, 1) : ''
            })
          } else {
            this.orderList.forEach((ele, index) => {
              ele.classifyId == data.id ? this.orderList.splice(index, 1) : ''
            })
          }
        }
      } else {
        this.orderList.push(data)
      }
    },

    /**
     * 状态组
     */

    /**
     * 方法组
     */
    // 筛选tree
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    setbusinessType() {
      const { businessType } =
        this.activePageForm.modules[this.activePageForm.activeModuleIndex]
      this.businessType = businessType
      this.treeProps.label = businessType == 'MALL' ? 'title' : 'name'
    },
    // 获取所有门店
    async getShopList() {
      await getAllShop({}).then((res) => {
        this.shopList = res.data
        this.shopId = res.data[0].id
      })
      await this.getProClass()
    },
    async getProClass() {
      const { shopId } = this
      await getClassifyList({ shopId, pageNum: 1, pageSize: 999 }).then(
        (res) => {
          this.treeData = res.data.total > 0 ? res.data.row : []
          // 设置默认勾选
          // this.$refs.categoryTree.setCheckedKeys()
        }
      )
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.tree-content {
  overflow: auto;
  max-height: 600px;
  font-size: 14px;
}
</style>
